package com.opdar.seed.idoc.utils;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

/**
 * Created by 俊帆 on 2015/8/25.
 */
public class CacheUtils {
    private final static CacheManager cacheManager = CacheManager.create();
    public static final String USERS = "users";

    static{
        Cache cache = new Cache(USERS,1,false,true,0,0);
        cacheManager.addCache(cache);
    }

    public static void cache(String key, Object value, int expire) {
        Element element = new Element(key, value);
        element.setTimeToLive(expire);
        Cache cache = cacheManager.getCache(USERS);
        if(cache.isElementInMemory(key)){
            cache.remove(key);
        }
        cache.put(element);

    }

    public static Object getCache(String key) {
        Cache cache = cacheManager.getCache(USERS);
        Element element = cache.get(key);
        if(element != null){
            return element.getObjectValue();
        }
        return null;
    }

    public static void remove(String key) {
        Cache cache = cacheManager.getCache(USERS);
        cache.remove(key);
    }

    public static void expire(String key,int expire) {
        Cache cache = cacheManager.getCache(USERS);
        Element element = cache.get(key);
        element.setTimeToLive(expire);
    }
}
